// pages/car/car.js

let util = require('../../utils/util')

const app = getApp()

Page({
  /**
   * 页面的初始数据
   */
  data: {
    handle_status: false,
    productData: [],
    allMoney: 0,
    allCount: 0,
    productAllMoney: 0,
    proCount: [],
    allState: false,
    stateMoney: '0',
    selectState: 0,
    proAllState: [],
    errState: false,
    proimgUrl: '',
    gnumber: ''
  },

  //delete
  deletePro: function (e) {
    
    wx.showLoading({
      title: '处理中',
      mask: true
    })
    let that = this
    let productData = that.data.productData
    wx.request({
      url: that.data.url + 'ny_flow_cart.php?action=delete_cart', //轮播图
      data: {
        openid: app.globalData.opid,
        goods_id: e.currentTarget.dataset.id
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        console.log(res)
        that.productList()
        wx.hideLoading()
      }
    })
  },
  bindKeyInput: function (e) {
    let that = this
    let goods_number = that.data.productData.goods_number
    if (e.detail.value <= 0) {
      that.setData({
        goods_number: 1
      })
    }
  },
  //跳转详情页
  toProDc: (e) => {
    let id = e.currentTarget.dataset.goods_id
    wx.navigateTo({
      url: `../wholesale/wholesale?id=${id}`
    })
  },
  //加法
  add: function (e) {
    let that = this
    let data = this.data.productData
    let idx = e.currentTarget.dataset.index


    data[idx].goods_number++
    console.log(app.globalData.opid)
    console.log(data[idx].goods_number)
    console.log(e.currentTarget.dataset.id)
    wx.request({
      url: app.globalData.url + 'ny_flow_cart.php?action=update_cart',
      data: {
        openid: app.globalData.opid,
        color_id: e.currentTarget.dataset.id,
        goods_number: data[idx].goods_number
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        console.log(res)
        if (res.data.errcode == 0) {
          wx.showToast({
            title: '修改数量成功',
            mask: true,
            duration: 1000,
            icon: 'none'
          })
          // data[idx].goods_number--
          that.setData({
            productData: data,
          })
        }
        that.productList()
        that.calcMoney()
      }
    })
  },
  //购物车删除
  deleteBtn: function (e) {
    let that = this
    let data = this.data.productData
    let idx = e.currentTarget.dataset.index
    data[idx].goods_number--
    wx.showModal({
      title: '提示',
      content: '确定要删除吗？',
      success: function (sm) {
        if (sm.confirm) {
          wx.request({
            url: app.globalData.url + 'ny_flow_cart.php?action=delete_cart',
            data: {
              openid: app.globalData.opid,
              goods_id: data[idx].rec_id
            },
            header: {
              'content-type': 'application/json' // 默认值
            },
            success: function (res) {
              that.productList()
            }
          })
          wx.showToast({
            title: '删除成功',
            mask: true,
            duration: 1000,
            icon: 'success'
          })
          let productData = that.data.productData;
          productData.splice(idx, 1)
          that.setData({
            productData: productData
          })

        } else if (sm.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  // 长按删除
  longtag:function(e){
    var that = this;
    console.log(e)
    let data = this.data.productData
    let idx = e.currentTarget.dataset.index;
    data[idx].delesta = true
    that.setData({
      productData:data
    })
  },
  // 取消删除
  cennel_delete:function(e){
    var that = this;
    console.log(e)
    let data = this.data.productData
    let idx = e.currentTarget.dataset.index;
    data[idx].delesta = false
    that.setData({
      productData: data
    })
  },
  //减法
  sub: function (e) {
    let that = this
    let data = this.data.productData
    let idx = e.currentTarget.dataset.index
    data[idx].goods_number--
    console.log(data[idx].goods_number)
    if (data[idx].goods_number <= 0) {
      wx.showModal({
        title: '提示',
        content: '确定要删除吗？',
        success: function (sm) {
          if (sm.confirm) {
            wx.request({
              url: app.globalData.url + 'ny_flow_cart.php?action=delete_cart',
              data: {
                openid: app.globalData.opid,
                goods_id: data[idx].rec_id
              },
              header: {
                'content-type': 'application/json' // 默认值
              },
              success: function (res) {
                console.log(res)
              }
            })
            wx.showToast({
              title: '删除成功',
              mask: true,
              duration: 2000,
              icon: 'success'
            })
            let productData = that.data.productData;
            productData.splice(idx, 1)
            that.setData({
              productData: productData
            })
          } else if (sm.cancel) {
            let productData = that.data.productData
            for (let i = 0; i < productData.length; i++) {
              if (productData[i].goods_number <= 0) {
                productData[i].goods_number = 1
              }
            }
            that.setData({
              productData: productData
            })
          }
        }
      })
    } else {
      wx.request({
        url: app.globalData.url + 'ny_flow_cart.php?action=update_cart',
        data: {
          openid: app.globalData.opid,
          color_id: e.currentTarget.dataset.id,
          goods_number: data[idx].goods_number
        },
        header: {
          'content-type': 'application/json' // 默认值
        },
        success: function (res) {
          if (res.data.errcode == 0) {
            wx.showToast({
              title: '修改数量成功',
              mask: true,
              duration: 1000,
              icon: 'none'
            })
            that.setData({
              productData: data,
            })
          }
          that.calcMoney()
          // that.productList()
        }
      })

    }

  },
  //单个店铺数量
  proCount: function () {

  },
  //全部数https://rt.gzziyu.com//mobile/ny_flow_cart.php?action=checkout_cart量
  allNum: function (num) {

  },
  parseMoney: function () {


  },
  toDecimal2(x) {
    var f = parseFloat(x);
    if (isNaN(f)) {
      return false;
    }
    var f = Math.round(x * 100) / 100;
    var s = f.toString();
    var rs = s.indexOf('.');
    if (rs < 0) {
      rs = s.length;
      s += '.';
    }
    while (s.length <= rs + 2) {
      s += '0';
    }
    return Number(s);
  },

  /**
   * 生命周期函数--监听页面加载
   */

  selectAll: function (e) {
    let data = this.data.productData
    if (!this.data.allState) {
      data.map((item, i) => {
        item.radio = true
      })
      this.setData({
        productData: data,
        allState: true
      })
    } else {
      data.map((item, i) => {
        item.radio = false
      })
      this.setData({
        productData: data,
        allState: false
      })
    }
    this.calcMoney()
  },
  select: function (e) {
    let idx = e.currentTarget.dataset.index
    let data = this.data.productData

    data[idx].radio = !data[idx].radio
    this.setData({
      productData: data
    })
    this.calcMoney()
    for (var i = 0; i < data.length; i++) {
      if (!data[i].radio) {
        this.setData({
          allState: false
        })
        this.calcMoney()
        return
      } else {
        this.setData({
          allState: true
        })
        this.calcMoney()
      }
    }

  },




  proSele: function (e) {


  },


  productList: function () {
    let that = this

    wx.request({
      url: that.data.url + 'ny_flow_cart.php?action=get_cart_info',
      data: {
        openid: app.globalData.opid
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      method: 'GET',
      success: function (res) {
        console.log(res)
        if(res.data.goods_list){
          var data = res.data.goods_list;
          for (var index in data) {
            data[index].delesta = false
          }
          that.setData({
            productData: data
          })
          that.calcMoney()
        }
        
        that.calcMoney()
        console.log(data)        
        wx.hideLoading()
      }
    })

  }
  ,
  calcMoney: function () {
   
    let data = this.data.productData;
    console.log(data)
    let num = 0
    data.map((item, i) => {
      if (item.radio) {
        num += Number(item.goods_price) * Number(item.goods_number)
      }
    })
    this.setData({
      allMoney: num.toFixed(2)
    })
  },
  onLoad: function (options) {
    let that = this
    let proimgUrl = app.globalData.url.replace('mobile/', '')
    console.log(that.data.productData)
    that.setData({
      url: app.globalData.url,
      proimgUrl: proimgUrl

    })
    console.log(app.globalData.opid)


    wx.showLoading({
      title: '加载中',
      mask: true
    })

    this.productList()
    

  },

  formatNumber: function (str) {
    return String(str).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
  },

  toDetails: function () {
    console.log(2);
  },
  toMenu: function () {
    wx.switchTab({
      url: '../../pages/mine/mine'
    })
  },

  clearing: function () {
    const productData = this.data.productData;
    console.log(productData)

    let sendData = JSON.parse(JSON.stringify(productData))

    
    sendData.map((item, i) => {
      item.openid = app.globalData.opid
    })

    sendData = sendData.filter((item, i) => {
      return item.radio
    })
   
    
    if (!sendData.length) {
      wx.showToast({
        title: '请选择商品',
        icon: 'none',
        duration: 2000
      })
      wx.hideLoading()
      return

    }
    console.log(JSON.stringify(sendData))
    let obj = {
      openid: app.globalData.opid,
      goods_id: sendData.goods_id,
      goods_name: sendData.goods_name,
      goods_info: sendData.goods_attr
    }
    wx.request({
      url: app.globalData.url + 'ny_flow_cart.php?action=checkout_cart',
      method: 'POST',
      data: {
        name: JSON.stringify(sendData)
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success: function (res) {
        console.log(res)
        wx.navigateTo({
          url: './../submit_order/submit_order'
        })

      }
    })

  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    getCurrentPages()[getCurrentPages().length - 1].onLoad()
    this.setData({
      allState: false,
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})